<template>
  <!-- 正常单据 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select ref="qtype" v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="押金单号" value="depositCode" />
          <el-option label="备注" value="remark" />
          <el-option label="经办人" value="transactor" />
          <el-option label="商品描述" value="goodsDesc" />
          <el-option label="收款人" value="depReceiver" />
          <el-option label="收据单号" value="billCode" />
          <el-option label="退款人" value="operator" />
          <el-option label="身份证号" value="csmCardNo" />
          <el-option label="组号" value="groupCode" />
          <el-option label="开户电话" value="openAccountPhone" />
        </el-select>
        <el-input v-model.trim="param1" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select ref="timetype" v-model="timetype" style="width: 170px; margin-right: 2px;">
          <el-option label="押金登记时间" value="createTime" />
          <el-option label="开始时间" value="beginDt" />
          <el-option label="结束时间" value="endDt" />
          <el-option label="经办时间" value="transactDt" />
          <el-option label="审核时间" value="auditDt" />
          <el-option label="消单时间" value="operateDt" />
          <el-option label="提瓶时间" value="takeBottleDt" />
          <el-option label="出库时间" value="outTime" />
          <el-option label="主体变更时间" value="subjectChangeTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select
          v-model="orgSNNo_qtype"
          style="width: 170px;"
        >
          <el-option value="returnOrgSNNo" label="退瓶机构" />
          <el-option value="ckOrgSNNo" label="押瓶机构" />
        </el-select>
        <el-tree-select
          v-model="ckOrgSNNo"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="押金来源:" class="merge-item">
        <el-select ref="fromPlat " v-model="query.fromPlat" placeholder="请选择" clearable>
          <el-option label="运气到家" :value="1" />
          <el-option label="微信公众号" :value="2" />
          <el-option label="支付宝小程序" :value="3" />
          <el-option label="好运气平台" :value="4" />
          <!-- <el-option label="CRM平台" :value="5" /> -->
          <el-option label="APP" :value="6" />
          <el-option label="微信小程序" :value="7" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:" class="merge-item">
        <el-select ref="csmType" v-model="query.csmType" clearable placeholder="请选择">
          <el-option v-for="(v,i) in entTypeList" :key="i" :label="v.desc" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态:" class="merge-item">
        <el-select ref="depStatus" v-model="query.depStatus" placeholder="请选择" clearable>
          <el-option v-for="(v,i) in depositStatusMap" :key="i" :label="v.desc" :value="v.value" />
          <!-- <el-option label="未审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已消单" :value="3" />
          <el-option label="已作废" :value="4" />
          <el-option label="审核不通过" :value="5" />
          <el-option label="消单待确认" :value="6" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="排序:" class="merge-item" placeholder="请选择">
        <el-select ref="orderby" v-model="query.orderby" clearable>
          <el-option label="押金登记时间" :value="2" />
          <el-option label="开始时间" :value="3" />
          <el-option label="结束时间" :value="4" />
          <el-option label="经办时间" :value="5" />
          <el-option label="审核时间" :value="6" />
          <el-option label="消单时间" :value="7" />
          <el-option label="提瓶时间" :value="8" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" class="merge-item">
        <el-select ref="paymentMethod" v-model="query.paymentMethod" placeholder="请选择" clearable>
          <el-option label="现金" :value="1" />
          <el-option label="微信支付" :value="2" />
          <el-option label="支付宝" :value="128" />
          <el-option label="门店扫码" :value="2048" />
          <el-option label="银行支付" :value="1024" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态:" class="merge-item">
        <el-select ref="payStatus" v-model="query.payStatus" placeholder="请选择" clearable>
          <el-option label="已支付" :value="3" />
          <el-option label="未支付" :value="1" />
          <el-option label="预支付" :value="2" />
          <el-option label="退款失败" :value="4" />
          <el-option label="已退款" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="签约状态:" class="merge-item">
        <el-select ref="isSign " v-model="query.isSign" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="提瓶状态:" class="merge-item">
        <el-select ref="isTakeBottle " v-model="query.isTakeBottle" placeholder="请选择" clearable>
          <el-option label="是" :value="2" />
          <el-option label="否" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="主体变更:" class="merge-item">
        <el-select ref="isSubjectChange " v-model="query.isSubjectChange" placeholder="请选择" clearable>
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="提瓶人:" class="merge-item">
        <el-select ref="takeBottleUser" v-model="query.takeBottleUserId" :loading="$loadingPlugin.getOwnersList" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库状态:" class="merge-item">
        <el-select ref="outStatus " v-model="query.outStatus" placeholder="请选择" clearable>
          <el-option label="是" :value="2" />
          <el-option label="否" :value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="回执状态:" class="merge-item">
        <el-select ref="reStatus " v-model="query.reStatus" placeholder="请选择" clearable>
          <el-option
            v-for="item in reStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <template v-slot:btns>
        <el-button v-permission="[20202,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;">
      <el-button v-permission="[20202,2]" type="primary" icon="el-icon-circle-plus-outline" @click="openNormalReceiptsAdd">新增</el-button>
      <!-- <el-button type="primary" icon="el-icon-s-check">批量审核</el-button> -->
      <!-- <el-button v-permission="8" type="primary" icon="el-icon-download" @click="exportFile(0)">导出</el-button>
      <el-button v-permission="24" type="primary" icon="el-icon-download" @click="exportFile(1)">非脱敏导出</el-button> -->
    </div>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      class="deposit-lbTable"
      border
      height="250"
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data.rows"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      :immediate-fetch="false"
      :row-class-name="tableRowClassName"
      @fetch="fetchData"
    />

    <normal-receipts-add ref="normalReceiptsAdd" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" @upDataTable="upDataTable" />
    <popups ref="popups" :ent-type-list="entTypeList" :tree-data="treeData" :calc-type-list="calcTypeList" :payment-method-list="paymentMethodList" :pay-status-list="payStatusList" :paymen-fil-list="paymenFilList" :customer-type="customerType" :parent-fetch-data="upDataTable" />
    <receipt ref="receipt" @upDataReceipt="upDataTable" />
    <depositAudit ref="depositAudit" :calc-type-list="calcTypeList" :pay-status-list="payStatusList" :payment-method-list="paymentMethodList" @depUpDataTable="upDataTable" />
    <orderConfirmation ref="orderConfirmation" :calc-type-list="calcTypeList" @upDataTable="upDataTable" />
    <orderConfirmationNew ref="orderConfirmationNew" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" :tree-data="treeData" @turnUpDataTable="upDataTable" />
    <transferInformation ref="transferInformation" />
    <turnOrder ref="turnOrder" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" :tree-data="treeData" @turnUpDataTable="upDataTable" />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <!-- <depositEdit ref="depositEdit" :calc-type-list="calcTypeList" :payment-method-list="paymentMethodList" :tree-data="treeData" /> -->
    <liftingBottle ref="liftingBottle" :tree-data="treeData" @upDataTable="upDataTable" />
    <csmGroupDetail ref="csmGroupDetail" :csm-status-map="csmStatusMap" :csm-type-map="customerType" :sub-type-list="subTypeList" />
    <receipt-confirm ref="receiptConfirm" :payment-method-map="paymenFilList" />
    <auditedEdit ref="auditedEdit" :calc-type-list="calcTypeList" :pay-status-list="payStatusList" :payment-method-list="paymentMethodList" @depUpDataTable="upDataTable" />
  </div>
</template>

<script>
  import NormalReceiptsAdd from '@/views/components/NormalReceiptsAdd'
  import { formatColumnMap, parseTime } from '@/utils'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import Popups from './Popups'
  import Receipt from './Receipt'
  import DepositAudit from './DepositAudit'
  import OrderConfirmation from './OrderConfirmation'
  import TransferInformation from './TransferInformation'
  import TurnOrder from './TurnOrder'
  import orderConfirmationNew from './orderConfirmationNew'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import liftingBottle from './liftingBottle'
  import { queryTheDepositList, queryCashPledgeObtainExport, queryExportDomain, queryRevertReturn, queryRevertAudit, queryCashPledgeInvalid, customerInfo, queryCashPledgeDetail, showEleContact, depositCancelTakeBottle, queryOwnersList, customerAttachment,
           depositTakeOutBottle, depositCancelTakeOutBottle, depositExcreteDepositCodes, queryMap } from '@/api'
  import { mapGetters } from 'vuex'
  // import moment from 'dayjs'
  import linkage from '@/assets/linkage.png'
  import csmGroupDetail from '../../customerManage/components/csmGroupDetail.vue'
  import ReceiptConfirm from './ReceiptConfirm'
  import auditedEdit from './auditedEdit'

  export default {
    name: 'normal-receipts-tab',
    components: {
      Popups, NormalReceiptsAdd, Receipt, DepositAudit, OrderConfirmation, TransferInformation, TurnOrder, CsmDetail, liftingBottle, orderConfirmationNew,
      csmGroupDetail,
      ReceiptConfirm,
      auditedEdit
    },
    props: {
      entTypeList: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      calcTypeList: {
        type: Array,
        required: true
      },
      paymentMethodList: {
        type: Array,
        required: true
      },
      payStatusList: {
        type: Array,
        required: true
      },
      paymenFilList: {
        type: Array,
        required: true
      },
      customerType: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        readOnly: false,
        qtype: 'csmPhone',
        actionColWidth: 80,
        param1: '',
        timetype: 'createTime',
        exportDomain: {},
        date: [],
        deriveParamInfo: {}, // 导出数据需要的状态
        ownersList: [], // 提瓶人
        ckOrgSNNo: '',
        orgSNNo_qtype: 'ckOrgSNNo',
        csmStatusMap: [],
        reStatusMap: [],
        query: {
          csmType: '', // 客户类型
          depositCode: '',
          depStatus: '',
          payStatus: '',
          paymentMethod: '',
          orderby: 2,
          createTime: '',
          createTimeEnd: '',
          isSign: '',
          isTakeBottle: '',
          isSubjectChange: '',
          fromPlat: '',
          takeBottleUserId: ''
        },
        depositStatusMap: [
          { 'value': 1, 'desc': '未审核', 'key': 'NOT_AUDIT' },
          { 'value': 2, 'desc': '已审核', 'key': 'AUDITED' },
          { 'value': 3, 'desc': '已消单', 'key': 'RETURNED' },
          // { 'value': 4, 'desc': '已作废', 'key': 'RETURNED' },
          { 'value': 5, 'desc': '审核不通过', 'key': 'NOT_PASS' },
          { 'value': 6, 'desc': '消单待确认', 'key': 'RETURN_APPLY' },
          { 'value': 9, 'desc': '作废待确认', 'key': 'VOID_APPLY' }
        ],
        tableData: {
          total: 0,
          data: {
            rows: []
          }
        },
        subTypeList: [
          {
            label: '餐饮',
            value: 1
          },
          {
            label: '餐饮(个人)',
            value: 2
          },
          {
            label: '工厂',
            value: 3
          },
          {
            label: '机关事业单位',
            value: 4
          },
          {
            label: '部队',
            value: 5
          },
          {
            label: '居民(个人)',
            value: 6
          },
          {
            label: '学校',
            value: 7
          },
          {
            label: '其他商业',
            value: 8
          },
          {
            label: '餐饮(连锁)',
            value: 9
          },
          {
            label: '住宿业',
            value: 10
          },
          {
            label: '商贸服务业',
            value: 11
          },
          {
            label: '医疗卫生',
            value: 12
          },
          {
            label: '社会保障',
            value: 13
          }
        ]
      }
    },

    computed: {
      ...mapGetters([
        'corpSettingData'
      ]),
      column: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            prop: 'depositCode',
            label: '押金单号',
            fixed: 'left',
            width: 140,
            className: 'depositCode',
            render: (h, { row }) => {
              const self = this
              function isBtn() {
                if (self.$store.getters.userInfo && ((self.$store.getters.userInfo.utype & 0x01) === 0x01)) return true
                const currentRoute = self.$router.currentRoute
                if (!currentRoute.meta || (!currentRoute.meta.btnScopes)) return true
                const btnScopes = currentRoute.meta.btnScopes
                if (btnScopes.length === 1 && btnScopes[0] === 0) return true
                return btnScopes.some(btnScope => btnScope >> (7 - 1) & 0x01)
              }
              if (isBtn()) {
                return row.subType === 9 ? (<div class='depositCodeImg'>
                 <img src={ linkage} alt={''}/>
                        <div>
                    <el-link underline={false} onClick={() => this.showDeposit(row)}>{row.depositCode}</el-link>
                    {row.isSign === 1 && (
                    <i class='el-icon-document' onClick={() => this.showEleContact(row)}></i>
                    )}
                  </div>
              </div>) : (
                  // <div>
                  //   <el-link underline={false} onClick={() => this.showDeposit(row)}>{row.depositCode}</el-link>
                  //   {row.isSign === 1 && (<i class='el-icon-document' onClick={() => this.showEleContact(row)}></i>)}
                  // </div>
                        <div>
                    <el-link underline={false} onClick={() => this.showDeposit(row)}>{row.depositCode}</el-link>
                  </div>
              )
              } else {
                return row.subType === 9 ? (<div class='depositCodeImg'>
                 <img src={ linkage} alt={''}/>
                       <span>{row.depositCode}</span>
              </div>) : (
                       <span>{row.depositCode}</span>
              )
              }
            }
          },
          {
            prop: 'depositUrl',
            label: '电子合同',
            align: 'center',
            width: 50,
            render: (h, { row }) => <span >{row.isSign === 1 && (
                    <i class='el-icon-document' onClick={() => this.showEleContact(row)}></i>
                    )}</span>
          },
          {
            prop: 'isShare',
            label: '共享状态',
            formatter: row => {
              return row.isShare === 0 ? '非共享' : row.isShare === 1 ? '共享' : ''
            }
          },
          {
            prop: 'takeBottleUser',
            label: '提瓶人'
          },
          {
            prop: 'takeBottleDt',
            label: '提瓶时间',
            width: 150,
            render: (h, { row }) => <span>{ row.takeBottleDt && parseTime(row.takeBottleDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'outStatus',
            label: '出库状态 ',
            formatter: row => {
              return row.outStatus === 1 ? '否' : row.outStatus === 2 ? '是' : ''
            }
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 160
          },
          {
            prop: 'openAccountPhone',
            width: 110,
            label: '开户电话'
          },
          {
            prop: 'csmCardNo',
            label: '身份证号',
            width: 180
          },
          {
            prop: 'csmType',
            label: '客户类型',
            width: 100,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.entTypeList, 'value', row.csmType, 'desc') }</span>
          },

          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 130,
            align: 'center'
          },
          {
            prop: 'totalCount',
            label: '总数量',
            width: 80,
            align: 'right'
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 200
          },
          {
            prop: 'totalDeposit',
            align: 'right',
            label: '总押金',
            width: 120,
            render: (h, { row }) => {
              var totalDeposit = row.totalDeposit || '0.00'
              totalDeposit = (totalDeposit * 1).toFixed(2)
              return <span>{totalDeposit}</span>
            }
          },
          {
            prop: 'fee1',
            align: 'right',
            label: '手续费',
            width: 120,
            render: (h, { row }) => {
              var fee1 = row.fee1 || '0.00'
              fee1 = (fee1 * 1).toFixed(2)
              return <span>{fee1}</span>
            }
          },
          {
            prop: 'ckOrgName',
            label: '押瓶机构',
            width: 180
          },
          {
            prop: 'returnOrgName',
            label: '退瓶机构',
            width: 180
          },
          {
            prop: 'createTime',
            label: '押金登记时间',
            width: 200,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'depStatus',
            label: '单据状态',
            width: 110,
            render: (h, { row }) => <span style={this.statusFormat(row.depStatus)}>{ row.depStatus && formatColumnMap(this.depositStatusMap, 'value', row.depStatus, 'desc') }</span>
          },
          {
            prop: 'auditDt',
            label: '审核时间',
            width: 200,
            render: (h, { row }) => <span>{ (row.depStatus === 2 || row.depStatus === 3 || row.depStatus === 6) && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'isSign ',
            label: '签约状态',
            formatter: row => {
              return row.isSign === 1 ? '是' : '否'
            }
          },
          {
            prop: 'reStatus',
            label: '回执状态',
            render: (h, { row }) => (
            <span>
              {row.reStatus || row.reStatus === 0
                ? formatColumnMap(this.reStatusMap, 'value', row.reStatus, 'desc')
                : '无需回执'}
            </span>
          )
          },
          {
            prop: 'reCheckDt',
            label: '回执时间',
            width: 150,
            render: (h, { row }) => <span>{ row.reCheckDt && parseTime(row.reCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'beginDt',
            label: '开始时间',
            width: 140,
            render: (h, { row }) => <span>{ row.beginDt && parseTime(row.beginDt, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'endDt',
            label: '结束时间',
            width: 140,
            render: (h, { row }) => <span>{ row.endDt && parseTime(row.endDt, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'transactor',
            label: '经办人',
            width: 110
          },
          {
            prop: 'depReceiver',
            label: '收款人',
            width: 110
          },
          {
            prop: 'operator',
            label: '退款人',
            width: 110
          },
          {
            prop: 'transactDt',
            label: '经办时间',
            width: 140,
            render: (h, { row }) => <span>{ row.transactDt && parseTime(row.transactDt, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'outUser',
            label: '出库人'
          },
          {
            prop: 'outTime',
            label: '出库时间',
            width: 150,
            render: (h, { row }) => <span>{ row.outTime && parseTime(row.outTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'operateDt',
            label: '消单时间',
            width: 200,
            render: (h, { row }) => <span>{ (row.depStatus === 3 || row.depStatus === 6) && parseTime(row.operateDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'billCode',
            label: '收据单号',
            width: 110
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            width: 110,
            render: (h, { row }) => <span>{ row.paymentMethod && formatColumnMap(this.paymenFilList, 'value', row.paymentMethod, 'desc') }</span>
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            width: 110,
            render: (h, { row }) => <span>{ row.payStatus && formatColumnMap(this.payStatusList, 'value', row.payStatus, 'desc') }</span>
          },
          {
            prop: 'fromPlat',
            label: '押金来源',
            width: 110,
            formatter: row => {
              return row.fromPlat === 1 ? '运气到家' : row.fromPlat === 2 ? '微信公众号' : row.fromPlat === 3 ? '支付宝小程序' : row.fromPlat === 4 ? '好运气平台'
                : row.fromPlat === 5 ? 'CRM平台' : row.fromPlat === 6 ? 'APP' : row.fromPlat === 7 ? '微信小程序' : ''
            }
          },
          {
            prop: 'returnPaymentMethod',
            label: '退款方式',
            width: 110,
            formatter: row => {
              return row.returnPaymentMethod === 1 ? '现金' : row.returnPaymentMethod === 2 ? '微信支付' : row.returnPaymentMethod === 128 ? '支付宝' : row.returnPaymentMethod === 1024 ? '银行支付' : row.returnPaymentMethod === 2048 ? '门店扫码' : ''
            }
          },
          {
            prop: 'subjectChangeTime',
            label: '主体变更时间',
            width: 150,
            render: (h, { row }) => <span>{ row.subjectChangeTime && parseTime(row.subjectChangeTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'groupCode',
            label: '客户组号',
            width: 110,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.csmGroupDetail(row)}>{row.groupCode}</el-link>
          },
          {
            prop: 'groupName',
            label: '组名称',
            width: 110
          },
          {
            label: '操作',
            // align: 'left',
            className: 'action-col',
            fixed: 'right',
            width: 80,
            render: (h, { row, $index }) => {
              return (
                  <div>
                    {row.depStatus === 2 && row.reStatus === 2 && (<el-link v-permission={[20202, 3]} underline={false} size='mini' onClick={() => this.openReceiptConfirm(row, $index)}>回执确认</el-link>)}
                  </div>
                )
            }
          }
        ]
      }
    },
    watch: {
      $route: {
        handler: function(to, from) {
          this.reGetUrlParams()
        },
        deep: true
      }
    },
    async created() {
      await this.getExportDomain()
      this.queryOptionsMap()
      this.reGetUrlParams()
    },
    methods: {
      reGetUrlParams() {
        if (this.$route.query) {
          const urlParams = this.$route.query
          this.query.payStatus = urlParams.payStatus ? Number(urlParams.payStatus) : ''
          this.query.depStatus = urlParams.depStatus ? Number(urlParams.depStatus) : ''
        }
        this.search()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' })
        ])
        this.csmStatusMap = res1.data // 客户状态
        this.reStatusMap = res2.data // 回执状态
      },
      // 查询
      async search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查询提瓶人
      async getOwnersList(org) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId: org || -1,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.getOwnersList(value.orgId)
      },
      // 新增
      async openNormalReceiptsAdd() {
        await this.$refs.normalReceiptsAdd.open('', 'add')
      },
      // 图片
      onImage(row) {
        console.log('图片row', row)
        this.$refs.popups.open(row, 'img')
      },
      // 电子合同
      async showEleContact(row) {
        const res = await showEleContact({ depositCode: row.depositCode })
        const url = res.data
        var m = document.createElement('a')
        m.href = url
        m.target = '_blank'
        document.body.appendChild(m)
        m.click()
      },
      // 编辑
      async openNormalReceipts(row) {
        this.readOnly = true
        setTimeout(() => {
          this.readOnly = false
        }, 1000)
        console.log('编辑row', row)
        const res = await customerInfo({ csmCode: row.csmCode })
        // 查询押金单详情
        const res1 = await queryCashPledgeDetail({
          depCode: row.depositCode,
          depositId: row.depositId,
          depStatus: row.depStatus
        })
        console.log('详情res1', res1)
        const obj = {
          ...res.data, // 用户信息
          depositCode: row.depositCode, // 押金单号
          ckOrgSNNo: row.ckOrgSNNo, // 押瓶机构
          ckOrgName: row.ckOrgName,
          ckOrgId: row.ckOrgId,
          depReceiver: row.depReceiver, // 收款人
          beginDt: row.beginDt, // 开始时间
          calcType: row.calcType, // 收款方式
          fee1: row.fee1, // 手续费
          remark: row.remark,
          billCode: row.billCode, // 收据单号
          paymentMethod: row.paymentMethod, // 支付方式
          transactorId: row.transactorId, // 经办人
          transactor: row.transactor, // 经办人名称
          transactDt: row.transactDt, // 经办时间
          depositDetails: res1.data.depositDetails ? res1.data.depositDetails : [],
          depositId: row.depositId,
          csmRgPhone: res1.csmRgPhone,
          csmRgAddress: row.csmAddress,
          csmAddressId: res1.data.csmAddressId ? res1.data.csmAddressId : 0,
          fromPlat: row.fromPlat
        }
        console.log('编辑参数', obj)
        this.$refs.normalReceiptsAdd.open(obj, 'edit')
      },
      // 收款支付
      async openReceipt(row) {
        if (row.payStatus === 3) {
          this.$message.warning('当前订单已重复支付请勿重复支付')
          return
        }
        this.$refs.receipt.open(row)
        // if (row.fromPlat !== 4) {
        //   this.$message.warning('当前功能只支持门店订单收款')
        //   return
        // }
        // if (row.paymentMethod !== 2 && row.paymentMethod !== 128) {
        //   this.$message.warning('订单支付方式不是微信或者支付宝不允许收款')
        //   return
        // }
        // const res = await selectDepositByCode({ depositCode: row.depositCode })
        // if (res.status === 200) {
        // }
      },
      // 审核
      openDepositAudit(row) {
        this.$refs.depositAudit.open(row)
      },
      // 消单确认
      openOrderConfirmation(row) {
        this.$refs.orderConfirmation.open(row)
      },
      // 新消单确认
      openOrderConfirmationNew(row) {
        this.$refs.orderConfirmationNew.open(row)
      },
      // 更新表格
      upDataTable() {
        console.log('gengxinl ')
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 退瓶消单
      openTurnOrder(row) {
        this.$refs.turnOrder.open(row)
      },
      // 作废
      onCancellation(row) {
        this.$confirm('确认要执行操作吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryCashPledgeInvalid({
            depCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 押金明细
      showDeposit(row) {
        console.log('押金明细', row)
        this.$refs.popups.open(row, 'info')
      },
      // 租瓶反审核
      revertAudit(row) {
        this.$confirm('是否确定执行租瓶反审核操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryRevertAudit({
            depositCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 退瓶反消单
      revertReturn(row) {
        this.$confirm('是否确定执行退瓶反消单操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const { status } = await queryRevertReturn({
            depositCode: row.depositCode
          })
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        })
      },
      // 已审核编辑
      toAuditedEdit(row) {
        this.$refs.auditedEdit.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打印
      async  printDep(data) {
        const res = await queryCashPledgeDetail({
          depCode: data.depositCode,
          depositId: data.depositId,
          depStatus: data.depStatus
        })
        this.tryPrint(res.data)
      },
      async tryPrint(row) {
        var cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }

        var temp = cache['15']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }

        var printcmd = {
          'cmd': 2,
          'title': `正在对押金单${row.depositCode}进行打印`,
          'elements': []
        }
        printcmd = { ...printcmd, ...temp }
        row.beginDate = row.auditDt ? parseTime(row.auditDt, '{y}-{m}-{d}') : ''
        row.csmAddress = (row.csmAddress || '').replace(/.+?(省|市)/g, '')
        if (row.paymentMethod === 1) {
          row.paymentMethod = '现金'
        } else if (row.paymentMethod === 2) {
          row.paymentMethod = '微信支付'
        } else {
          row.paymentMethod = ''
        }
        var items = row.depositDetails
        var count1 = 0
        var count2 = 0
        var count3 = 0
        for (var i in items) {
          var item = items[i]
          if (item.goodsName.startsWith('5')) {
            count1++
          }
          if (item.goodsName.startsWith('15')) {
            count2++
          }
          if (item.goodsName.startsWith('50')) {
            count3++
          }
        }
        if (count1 === 0) {
          items.push({ 'goodsName': '5kg', 'goodsCount': 0 })
        }
        if (count2 === 0) {
          items.push({ 'goodsName': '15kg', 'goodsCount': 0 })
        }
        if (count3 === 0) {
          items.push({ 'goodsName': '50kg', 'goodsCount': 0 })
        }
        items.sort((a, b) => {
          var num1 = a.goodsName.replace(/[^0-9]/ig, '')
          var num2 = b.goodsName.replace(/[^0-9]/ig, '')
          return num2 - num1
        })
        row.deposit = items[0].deposit
        if (row.payStatus === 3) {
          row.printMoney = `${row.totalDeposit} 已支付${row.paymentMethod}`
        }
        if (row.csmType !== 1) {
          const res2 = await customerAttachment({ csmCode: row.csmCode })
          if (res2.data) {
            row.csmNewName = row.csmName + (res2.data.sfzName || '')
            if (res2.data.cardItems) {
              for (const i in res2.data.cardItems) {
                if (res2.data.cardItems[i].cardType === 4) {
                  row.csmNewCardNo = (res2.data.sfzh || '') + (res2.data.cardItems[i].cardNo || '')
                }
              }
            } else {
              row.csmNewCardNo = res2.data.sfzh || ''
            }
            window.jCPrint.process(printcmd, temp, row, items)
            if (window.jCPrint.send(JSON.stringify(printcmd))) {
              this.$message.success('打印指令已发送')
            } else {
              this.$message.error('打印未连接', 5000)
            }
          }
        } else {
          row.csmNewCardNo = row.csmCarNo
          row.csmNewName = row.csmName
          window.jCPrint.process(printcmd, temp, row, items)
          if (window.jCPrint.send(JSON.stringify(printcmd))) {
            this.$message.success('打印指令已发送')
          } else {
            this.$message.error('打印未连接', 5000)
          }
        }
      },
      async returnPrint(data, type) {
        const res = await queryCashPledgeDetail({
          depCode: data.depositCode,
          depositId: data.depositId,
          depStatus: data.depStatus
        })
        this.tryPrint1(res.data, type)
      },
      async tryPrint1(row, type) {
        var cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        var temp = ''
        if (type === 1) {
          temp = cache['32']
        } else {
          temp = cache['33']
        }
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }

        var printcmd = {
          'cmd': 2,
          'title': `正在对押金单${row.depositCode}进行打印`,
          'elements': []
        }
        printcmd = { ...printcmd, ...temp }
        var items = row.depositDetails
        var count1 = ''
        var count2 = ''
        var count3 = ''
        var count4 = ''
        var count5 = ''
        var count6 = ''
        for (var i in items) {
          var item = items[i]
          if (item.goodsName.startsWith('15')) {
            count1 = item.goodsCount
            count2 = item.deposit
            count5 = item.rental
          }
          if (item.goodsName.startsWith('50')) {
            count3 = item.goodsCount
            count4 = item.deposit
            count6 = item.rental
          }
        }
        row.count1 = count1
        row.count2 = count2
        row.count3 = count3
        row.count4 = count4
        row.count5 = count5
        row.count6 = count6
        var date1 = row.endDt ? parseTime(row.endDt, '{y}-{m}-{d}') : ''
        var date2 = row.beginDt ? parseTime(row.beginDt, '{y}-{m}-{d}') : ''
        date1 = date1.split('-')
        date1 = parseInt(date1[0]) * 12 + parseInt(date1[1]) * 1
        date2 = date2.split('-')
        date2 = parseInt(date2[0]) * 12 + parseInt(date2[1]) * 1
        if (count1) {
          row.month1 = Math.abs(date1 - date2) + 1
        }
        if (count3) {
          row.month2 = Math.abs(date1 - date2) + 1
        }
        row.csmNewCardNo = row.csmCardNo + '(卡号 ' + row.csmCode + ')'
        row.csmNewName = row.csmName
        row.operateDt = row.operateDt ? parseTime(row.operateDt, '{y}-{m}-{d} {h}:{i}') : ''
        row.signDt = row.operateDt ? parseTime(row.operateDt, '{y} {m} {d}') : ''
        window.jCPrint.process(printcmd, temp, row, items)
        if (window.jCPrint.send(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接', 5000)
        }
      },
      // 流转信息
      showTraceWin(row) {
        this.$refs.transferInformation.open(row)
      },
      // 列表
      async fetchData({ currentPage, pageSize }) {
        const query1 = JSON.parse(JSON.stringify(this.query))
        for (const key in query1) {
          if (key !== 'createTime' && key !== 'createTimeEnd' && key !== 'ckOrgSNNo' && key !== 'depositCode') {
            if (!query1[key]) {
              query1[key] = -1
            }
          }
        }
        const params = { ...query1 }
        params[this.qtype] = this.param1
        params[this.orgSNNo_qtype] = this.ckOrgSNNo
        if (this.date !== null) {
          if (this.date.length === 2) {
            params[this.timetype] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            params[`${this.timetype}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
        const query = {
          ...this._getQuery(params),
          reStatus: 2,
          currentPage,
          pageSize
        }
        // 导出数据需要的状态
        this.deriveParamInfo = {}
        this.deriveParamInfo = query
        const result = await queryTheDepositList(query)
        this.tableData.data.rows = result.data.rows
        if (currentPage === 1) {
          this.tableData.total = result.data.total
        }
        this.flexColumnWidth()
      },
      // 导出
      async exportFile(type) {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const currentPage = this.$refs.lbTable.currentPage
          const pageSize = this.$refs.lbTable.pageSize
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const query = {
            ...this._getQuery(this.deriveParamInfo),
            currentPage,
            pageSize
          }
          query[this.orgSNNo_qtype] = this.ckOrgSNNo
          query.desensitizeFlag = type
          console.log('query', query)
          console.log('query', str)
          queryCashPledgeObtainExport({
            paramInfo: query,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取导出域名
      async getExportDomain() {
        const res = await queryExportDomain()
        if (res && res.data) {
          this.exportDomain = res.data
        }
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 颜色
      statusFormat(val) {
        var colorObj = {
          '1': 'color:#0033ff;', // 待审核
          '2': 'color:#333333;', // 已审核
          '3': 'color:#666666;', // 已消单
          '4': 'color:#666666;', // 已作废
          '5': 'color:#ff0000;', // 审核不通过
          '6': 'color:#0033ff;' // 消单待确认
        }
        return colorObj[val]
      },
      // 支付状态
      payStatusFormat(r) {
        if (r.payStatus === 1) {
          return '未支付'
        } else if (r.payStatus === 3) {
          return '已支付'
        } else {
          return ''
        }
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 提瓶
      async liftingBottle(row) {
        await this.$refs.liftingBottle.open(row)
      },
      // 提瓶撤回
      liftingBottleReturn(row) {
        this.$confirm(`确认要执行操作吗`, '提示', {
          type: 'warning'
        }).then(() => {
          depositCancelTakeBottle({ depCode: row.depositCode }).then(res => {
            this.$message({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          })
        })
      },
      // 出库
      outStore(row) {
        this.$confirm(`请确认是否要进行出库操作`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          depositTakeOutBottle({ depositCode: row.depositCode }).then(res => {
            this.$notify({
              title: '提示',
              message: '操作成功!',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 出库撤回
      outStoreReturn(row) {
        this.$confirm(`请确认是否要进行出库撤销操作`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          depositCancelTakeOutBottle({ depositCode: row.depositCode }).then(res => {
            this.$notify({
              title: '提示',
              message: '操作成功!',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      // 拆单
      splitOrder(row) {
        this.$confirm(`当前押金单包含<strong style="color:red">${row.totalCount}</strong>个气瓶，是否为每个气瓶生成单独的押金单？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          depositExcreteDepositCodes({ depositCode: row.depositCode }).then(res => {
            this.$notify({
              title: '提示',
              message: '操作成功!',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      tableRowClassName({ row, rowIndex }) {
        if (row.depStatus === 1) return 'red-bg-row'
        else if (row.depStatus === 3) return 'gray-bg-row'
        else return ''
      },
      // 客户组
      async  csmGroupDetail(row) {
        await this.$refs.csmGroupDetail.open(row)
      },
      // 点击回执确认
      async openReceiptConfirm(row) {
        await this.$refs.receiptConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>

.deposit-lbTable {
  & /deep/ .el-table .depositCode {
    padding: 0;
    .depositCodeImg {
      display: flex;
      margin-left: -9px;
      img {
        width: 30px;
        height: auto;
      }
    }
  }
}
</style>
